package com.xframework.filter;

import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by xuning on 2021/2/8.
 */
@RestController
public class FilterExceptionController extends BasicErrorController {
    private static Map<String, Object> resp = new LinkedHashMap<String, Object>();

    public FilterExceptionController() {
        super(new DefaultErrorAttributes(), new ErrorProperties());
        System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx FilterExceptionController xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
        resp.put("code", 0);
    }

    @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> errorAttributes = getErrorAttributes(request, ErrorAttributeOptions.of(ErrorAttributeOptions.Include.EXCEPTION, ErrorAttributeOptions.Include.MESSAGE, ErrorAttributeOptions.Include.STACK_TRACE, ErrorAttributeOptions.Include.BINDING_ERRORS));
        HttpStatus status = getStatus(request);
        resp.put("result", errorAttributes.get("message").toString());
        return new ResponseEntity<>(resp, status);
    }
}
